from flask import Flask, request, jsonify
import joblib
import pandas as pd
import numpy as np
from datetime import datetime

app = Flask(__name__)

# 加载模型和相关对象
try:
    model = joblib.load('repurchase_model.pkl')
    scaler = joblib.load('scaler.pkl')
    feature_names = joblib.load('feature_names.pkl')
    print("模型和相关对象加载成功")
except FileNotFoundError:
    print("找不到模型文件，请先运行model_training.py训练模型")
    model = None

@app.route('/')
def home():
    return "用户复购预测API服务"

@app.route('/predict', methods=['POST'])
def predict():
    """预测用户复购概率"""
    if model is None:
        return jsonify({"error": "模型未加载，请先训练模型"}), 500
    
    # 获取请求数据
    data = request.json
    
    # 转换为DataFrame
    try:
        input_data = pd.DataFrame([data])
    except:
        return jsonify({"error": "输入数据格式不正确"}), 400
    
    # 确保所有特征都存在，不存在的用0填充
    for feature in feature_names:
        if feature not in input_data.columns:
            input_data[feature] = 0
    
    # 按特征名称排序
    input_data = input_data[feature_names]
    
    # 标准化
    input_scaled = scaler.transform(input_data)
    
    # 预测
    prediction_proba = model.predict_proba(input_scaled)[0][1]
    prediction_class = model.predict(input_scaled)[0]
    
    # 返回结果
    result = {
        "prediction_class": bool(prediction_class),  # 是否为复购用户
        "prediction_probability": float(prediction_proba),  # 复购概率
        "model_version": "1.0.0"
    }
    
    return jsonify(result)

@app.route('/metrics', methods=['GET'])
def get_metrics():
    """获取模型评估指标（示例数据）"""
    metrics = {
        "accuracy": 0.85,
        "precision": 0.88,
        "recall": 0.82,
        "f1_score": 0.85,
        "auc": 0.92
    }
    return jsonify(metrics)

@app.route('/explain', methods=['POST'])
def explain_prediction():
    """解释预测结果（特征重要性）"""
    if model is None:
        return jsonify({"error": "模型未加载，请先训练模型"}), 500
    
    # 获取请求数据
    data = request.json
    
    # 转换为DataFrame
    try:
        input_data = pd.DataFrame([data])
    except:
        return jsonify({"error": "输入数据格式不正确"}), 400
    
    # 确保所有特征都存在，不存在的用0填充
    for feature in feature_names:
        if feature not in input_data.columns:
            input_data[feature] = 0
    
    # 按特征名称排序
    input_data = input_data[feature_names]
    
    # 标准化
    input_scaled = scaler.transform(input_data)
    
    # 获取特征重要性
    if hasattr(model, 'feature_importances_'):
        importances = model.feature_importances_
    else:
        # 如果模型没有feature_importances_属性，使用系数的绝对值
        importances = np.abs(model.coef_[0])
    
    # 创建特征重要性排名
    importance_dict = {}
    for i, feature in enumerate(feature_names):
        importance_dict[feature] = float(importances[i])
    
    # 按重要性排序
    sorted_importance = sorted(importance_dict.items(), key=lambda x: x[1], reverse=True)
    
    return jsonify({
        "feature_importance": sorted_importance[:10]  # 返回前10个重要特征
    })

if __name__ == '__main__':
    app.run(debug=True)    